const router = require('koa-router')(),
  fs = require('fs'),
  path = require('path'),
  log = console.log,
  { loopDelete, listFilesAndDirs } = require('../utils/filesApi')


const dirinfo = {}
router.get('/init', async (ctx, next) => {
  const userId = ctx.user.id
  log(userId)
  log(dirinfo)
  if (!dirinfo[userId]) {
    //第一次登陆 默认在 在自己的id下
    const serverPath = path.join(__dirname, '../', 'server', `${userId}`);
    //使用 process.chdir 改变当前工作目录
    process.chdir(serverPath)
    log(process.cwd())
    dirinfo[userId] = serverPath
    log(dirinfo)
  } else {
    //不是第一次登录默认切换到状态值下
    log('run it')
    process.chdir(dirinfo[userId])
  }
  ctx.body = '初始化完成'
})

router.post('/upload/:filename', async (ctx, next) => {
  const fileName = ctx.params.filename
  const userId = ctx.user.id
  try {
    const writeStream = fs.createWriteStream(path.join(dirinfo[userId], `${fileName}`))
    await new Promise((rv, rj) => {
      ctx.req.pipe(writeStream);
      ctx.req.on('end', () => {
        writeStream.end(); // 结束写入流
      })
      writeStream.on('finish', () => {
        rv();
      });
      writeStream.on('error', error => {
        rj(error);
      });
    })
      .then(() => {
        ctx.body = '上传成功\n'
      }).catch((error) => {
        ctx.body = error
      });
  } catch (error) {
    ctx.status = 500;
  }
})

router.get('/download/:file', async (ctx, next) => {
  const filename = ctx.params.file
  const userId = ctx.user.id
  try {
    const absolutePath = path.join(dirinfo[userId], `${filename}`) 
    if (!fs.existsSync(absolutePath)) {
      ctx.status = 404
      ctx.body = "要下载的文件不存在，请重新输入文件名字\n"
    } else {
      ctx.body = fs.createReadStream(absolutePath)
    }
  } catch (error) {
    ctx.body = error
  }
})

router.delete('/delete/:file', async (ctx, next) => {
  const filename = ctx.params.file
  const userId = ctx.user.id
  const absolutePath = path.join(dirinfo[userId], `${filename}`) 
  console.log(absolutePath)
  if (!fs.existsSync(absolutePath)) {
    ctx.body = { status: 1, msg: "要删除的文件或者目录不存在，请重新输入名字" }
  } else {
    if (fs.statSync(absolutePath).isFile()) {
      fs.unlinkSync(absolutePath)
      ctx.body = { status: 0, msg: '文件删除成功' }
    } else {
      loopDelete(absolutePath)
      fs.rmdirSync(absolutePath)
      ctx.body = { status: 0, msg: '目录删除成功' }
    }
  }
})

router.put('/rename', async (ctx, next) => {
  const { oldName, newName } = ctx.request.body;
  const userId = ctx.user.id
  console.log(oldName, newName)
  if (!fs.existsSync(path.join(dirinfo[userId], `${oldName}`))) {
    ctx.status = 404
    ctx.body = { status: 1, msg: "文件不存在无法改名字" }
  } else {
    try {
      const oldabsolutePath = path.join(dirinfo[userId], `${oldName}`)
      console.log(oldabsolutePath)
      const newabsolutePath = path.join(dirinfo[userId], `${newName}`)
      console.log(newabsolutePath)
      fs.renameSync(oldabsolutePath, newabsolutePath);
      ctx.body = { status: 0, msg: "文件名修改成功" }
    } catch (error) {
      ctx.body = { status: 1, msg: 'guo' }
    }
  }
})

router.post('/mkdir', async (ctx, next) => {
  const { name } = ctx.request.body
  const userId = ctx.user.id
  try {
    const filePath = path.join(dirinfo[userId], `${name}`)
    fs.mkdirSync(filePath);
    ctx.body = { status: 0, msg: '创建目录成功' }
  } catch (error) {
    ctx.body = { status: 1, msg: "创建目录失败" }
  }
})

router.get('/list', async (ctx, next) => {
  const userId = ctx.user.id
  const arr = listFilesAndDirs(dirinfo[userId])
  ctx.body = arr
})


router.post('/lcd', async (ctx, next) => {
  //修改的本地目录
  //<dir> 传过来 的绝对路径 我要到dir这个目录下
  const { name, currentpath } = ctx.request.body  
  log(name)
  log(currentpath)//绝对路径
  if (!fs.existsSync(currentpath)) {
    ctx.status = 404
    ctx.body = { status: 1, msg: "目录不存在 修改切换失败" }
  } else {
    try {
      const abspath = path.join(currentpath, name)
      process.chdir(abspath);
      log(process.cwd());
      ctx.body = { status: 0, msg: "修改切换成功", abspath }
    } catch (err) {
      ctx.body = { status: 1, msg: err }
    }

  }
})
router.post('/rcd', async (ctx, next) => {
  //修改的服务器的目录
  //<dir> 传过来 的绝对路径 我要到dir这个目录下
  const userId = ctx.user.id
  const { dir } = ctx.request.body
  console.log(dir) //kkk
  console.log(process.cwd())
  if (!fs.existsSync(path.join(dirinfo[userId], `${dir}`))) {
    ctx.body = { status: 1, msg: "不存在这个目录，修改切换失败" }
  } else {
    try {
      dirinfo[userId] = path.join(dirinfo[userId], `${dir}`)
      process.chdir(dirinfo[userId]);
      console.log(process.cwd())
      console.log(dirinfo)
      ctx.body = { status: 0, msg: "修改切换成功" }
    } catch (err) {
      ctx.body = { status: 1, msg: err }
    }
  }
})
router.get('/rpwd', async (ctx, next) => {
  const userId = ctx.user.id
  ctx.body = dirinfo[userId];
})



module.exports = router
